<script lang="ts" setup>
import {onMounted, ref, watch} from 'vue';
import {useRoute} from 'vue-router';
import {useArticleListStore} from '@/stores/articleListStore';
import ArticlePrevNext from "@/components/pageElement/ArticlePrevNext.vue";
import {api} from "@/utils/api";
import ArticleContentLayout from "@/layouts/ArticleContentLayout.vue";

const props = withDefaults(defineProps<{
  isPdf?: boolean; // 是否为 PDF 文章
}>(), {
  isPdf: false
});

const route = useRoute();
const articleListStore = useArticleListStore();
const locationStore = useLocationStore();

const articleData = ref<Article | null>(null);
const pdfData = ref<string | undefined>(undefined);

const nextArticle = ref<ArticleRecord | null>(null);
const prevArticle = ref<ArticleRecord | null>(null);

const updatePrevNextArticles = async () => {
  prevArticle.value = await articleListStore.peekPreviousArticle();
  nextArticle.value = await articleListStore.peekNextArticle();
};

const loadArticle = async () => {
  const query = route.query;

  let articleId: number | null = null;

  // 优先尝试直接获取 "articleId"
  if (query.articleId) {
    articleId = parseInt(query.articleId as string, 10);
  }

  // 如果直接的 "articleId" 不存在或解析失败，尝试匹配 "articleId_开头" 的参数
  if ((!articleId || isNaN(articleId))) {
    for (const key in query) {
      if (key.startsWith('articleId_')) {
        articleId = parseInt(query[key] as string, 10);
        if (!isNaN(articleId)) {
          break; // 找到有效的 articleId 后停止遍历
        }
      }
    }
  }

  if (!articleId) return;

  try {
    const response = await api.getNewsCenterById(articleId);
    if (response.code === 1) {
      articleData.value = response.data;

      if (props.isPdf && articleData.value?.pdfFileName) {
        pdfData.value = await api.getResourceByPath(articleData.value.pdfFileName);
      }

      // 如果为文章链接直接跳转，则加载第一页（首页展示的就是第一页数据）
      if (route.query.from === 'direct') {
        articleListStore.articleCategory = locationStore.name
        await articleListStore.loadArticles(1);
      }

      // 更新 currentArticleIndex，如果文章不在当前列表中，需要重新加载列表
      await articleListStore.setCurrentArticleIndex(articleId);

      // 更新前后页数据
      await articleListStore.loadPrevNextPages();

      // 更新上一篇和下一篇文章
      await updatePrevNextArticles();
    } else {
      console.error("Failed to fetch article:", response.msg);
    }
  } catch (error) {
    console.error("Error loading article:", error);
  }
};


// 每次文章 ID 发生变化时重新加载文章
onMounted(() => {
  loadArticle();
});

watch(() => route.query.articleId, async () => {
  await loadArticle();
});
</script>

<template>
  <article-content-layout>
    <div class="main">
      <h2>{{ articleData?.title }}</h2>
      <ul class="cont-title">
        <li>
          <span>发布时间：{{ articleData?.createTime }}</span>
          <span>更新时间：{{ articleData?.updateTime }}</span>
        </li>
      </ul>
      <div class="content">
        <iframe v-if="isPdf&&pdfData" :src="pdfData" width="100%" height="900"></iframe>
        <div v-else class="v_news_content" v-html="articleData?.details"></div>
        <ArticlePrevNext
            :current-page-route-name="String(route.name)"
            :next-article="nextArticle"
            :previous-article="prevArticle"
        />
      </div>
    </div>
  </article-content-layout>
</template>

<style scoped>
/* 样式代码 */
</style>
